package br.com.spring.mvc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.ui.Model;
import org.springframework.validation.ObjectError;

import br.com.spring.mvc.entity.infra.Message;
import br.com.spring.mvc.entity.infra.TypeMessage;

import com.google.gson.Gson;

public class BaseController {

	private Map<String, Object> attributes = new HashMap<String, Object>();
	private List<Message> messages = new ArrayList<Message>();	
	private Model model;
	
	protected String getAttributesFromJson(){
		attributes.put("messages",messages);
		String attributesFromJson = convertToJson(attributes);
		return attributesFromJson;
	}
	
	protected void getAttributes(){
		model.addAllAttributes(attributes);
		model.addAllAttributes(messages);
	}
	
	protected void setAttributes(Model model){
		this.model = model;
	}
	
	protected void addAttribute(String attributeName, Object attribute){
		attributes.put(attributeName, attribute);
	}
	
	protected void addMessage(Message message){
		messages.add(message);		
	}
	
	@SuppressWarnings("rawtypes")
	protected void addError(List<ObjectError> erros) throws Exception{
		for (Iterator iterator = erros.iterator(); iterator.hasNext();) {
			ObjectError objectError = (ObjectError) iterator.next();
			Message message = new Message(TypeMessage.ERROR, objectError.getDefaultMessage());
			messages.add(message);
		}
		if(messages.size() > 0){throw new Exception();}
	}
	
	protected String convertToJson(Object object){		
		Gson json = new Gson();		
		return json.toJson(object);
	}
	
	public void clearAttributes(){
		attributes.clear();
		messages.clear();
	}
}
